package com.qianbei.view.bluetooth;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothClass;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.qianbei.R;
import com.qianbei.bean.RequeastBean1;
import com.qianbei.common.base.BaseActivity;
import com.qianbei.common.base.BaseApplication;
import com.qianbei.common.base.Basebean;
import com.qianbei.common.net.control.ServerControl;
import com.qianbei.common.net.control.ServerResult;
import com.qianbei.common.net.view.MsgAlert;
import com.qianbei.common.net.view.ProgressDialog;

import org.json.JSONException;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * <pre>
 *     author : pipi
 *     e-mail : xxx@xx
 *     time   : 2018/09/29
 *     desc   :
 *     version: 1.0
 * </pre>
 */

public class DeviceScanActivity extends BaseActivity {
    private static final String TAG = DeviceScanActivity.class.getSimpleName();
    public static final String EXTRA_DEVICE = "device";
    private static final int REQUEST_ENABLE_BT = 1;
    @Bind(R.id.listView)
    ListView mListView;
    private BluetoothAdapter mBluetoothAdapter;
    private boolean isScanning;
    private DeviceScanAdapter mAdapter;
    private ProgressDialog mProgressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device_scan);
        ButterKnife.bind(this);
        init();
    }

    private void init() {
        initReceiver();
        mAdapter = new DeviceScanAdapter(this);
        mListView.setAdapter(mAdapter);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                showProgress("正在连接...");
                BTDevice btDevice = mAdapter.getItem(position);
                BluetoothDevice bluetoothDevice = mBluetoothAdapter.getRemoteDevice(btDevice.getAddr());
                BluetoothService.getInstance().connect(bluetoothDevice);
            }
        });
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
            new MsgAlert().show("设备不支持蓝牙");
            finish();
            return;
        }
        setTitle("搜索蓝牙");
        BluetoothService.getInstance().setOnConnectListener(new BluetoothService.OnConnectListener() {
            @Override
            public void onConnectSuccess() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        new MsgAlert().show("蓝牙设备连接成功");
                        hideProgress();
                        finish();
                    }
                });
            }

            @Override
            public void onConnectFail() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        hideProgress();
                        new MsgAlert().show("蓝牙设备连接失败，请重新再试");
                    }
                });
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        } else {
            startScan();
        }
    }

    private void hideProgress() {
        if (mProgressDialog != null) {
            mProgressDialog.hide();
        }
    }

    private void showProgress(String tip) {
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.showProgress(tip);
    }

    /**
     * 开始扫描
     */
    private void startScan() {
        mBluetoothAdapter.startDiscovery();
        mAdapter.clear();
        mTitle.setrightTitle("正在扫描");
        showProgress("正在扫描...");
        isScanning = true;
    }

    private void initReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(mReceiver, filter);
    }

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                String rssi = "";
                if (intent.getExtras() != null) {
                    rssi = intent.getExtras().getShort(
                            BluetoothDevice.EXTRA_RSSI) + "";
                }
                BTDevice btDevice = new BTDevice();

                btDevice.setName(device.getName());
//                btDevice.setName(BaseApplication.mCarMap.get("431474138"));
                if (BaseApplication.mCarMap.size()>0){
                    if (device.getName()!=null) {
                        if (device.getName().startsWith("HD:")) {
                            String numb = device.getName().split("HD:")[1];
                            if (BaseApplication.mCarMap.containsKey(numb)) {
                                String carNum = BaseApplication.mCarMap.get(numb);
                                btDevice.setName(carNum);
                            }
                        }
                    }
                }else {
                    Toast.makeText(DeviceScanActivity.this,"获取蓝牙对应车牌失败，请重新扫描蓝牙设备！",Toast.LENGTH_SHORT).show();
                    getDeviceData();
                }

                btDevice.setAddr(device.getAddress());
                btDevice.setRssi(rssi);
                mAdapter.addData(btDevice);
                hideProgress();
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                mTitle.setrightTitle("扫描");
                hideProgress();
                isScanning = false;
            }
        }
    };

    public void getDeviceData(){

        RequeastBean1 bean = new RequeastBean1("select","com.cygps.dubbo.commons.data.ICommonDataService",new Basebean(),"WT_Bluetooth");

        ServerControl sc = new ServerControl(bean);
        sc.serverListener = new ServerControl.ServerListener() {
            @Override
            public void serverFinish(ServerResult sr) {
    //                Toast.makeText(HomeActivity.this,sr.bodyData.toString(),Toast.LENGTH_SHORT).show();
                Log.e("bodyData",sr.bodyData.toString());
                try {
                    org.json.JSONObject mObj = new org.json.JSONObject(sr.bodyData.toString());
                    org.json.JSONArray array = mObj.getJSONArray("array");
                    for (int i = 0; i < array.length(); i++) {
                        BaseApplication.mCarMap.put(array.getJSONObject(i).getString("bluetoothId"), array.getJSONObject(i).getString("vehicleNo"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        };
            sc.OKpost1();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mBluetoothAdapter != null) {
            mBluetoothAdapter.cancelDiscovery();
        }
        if (mProgressDialog != null) {
            mProgressDialog.close();
        }
        unregisterReceiver(mReceiver);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_ENABLE_BT) {
            if (resultCode == Activity.RESULT_OK) {
                startScan();
            } else {
                new MsgAlert().show("拒绝了开启蓝牙");
                finish();
            }
        }
    }

    @Override
    public void fClick(int id) {
        super.fClick(id);
        switch (id) {
            case R.id.tv_right:
                if (!isScanning) {
                    startScan();
                } else {
                    if (mBluetoothAdapter.isDiscovering()) {
                        mBluetoothAdapter.cancelDiscovery();
                    }
                    mTitle.setrightTitle("扫描");
                    hideProgress();
                }
                break;
        }
    }
}
